/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86187
 * Date: 2022-04-21
 * Time: 19:13
 */

//Scanner scan = new Scanner(System.in);

import java.util.Arrays;

public class TestDemo {

    public static void main(String[] args) {
        int[] array = new int[1_0000];
        for (int i = 0; i < array.length; i++) {
            array[i] = i;
        }

        //查找
        int m = Arrays.binarySearch(array,9999);//返回下标
        System.out.println(m);
    }

    /**
     * 二分查找，找到就返回小标，否则返回-1
     * 只能查找有序数组，这里是升序
     * @param arr
     * @param num
     * @return
     */
    public static int binarySearch(int[] arr,int num) {
        int left = 0;
        int right = arr.length-1;

        while(left <= right) {
            int mid = (left + right) / 2;
            if(arr[mid] < num) {
                left = mid + 1;
            } else if(arr[mid] == num){
                return mid;
            } else {
                right = mid - 1;
            }
        }
        //未找到
        return -1;
    }

    public static void main1(String[] args) {

        int[] arr = {5,9,12,45,56,78};

        int ret = binarySearch(arr,12);
        if(ret != -1) {
            System.out.println("该数下标为："+ret);
        } else {
            System.out.println("找不到该数！");
        }
    }
}
